#include "ds1302.h"

#define DS1302_DELAY	1
DATE cur_date;

void ds1302_init()
{
	P3MDOUT |= 0x0E;
	DS1302_DAT =1;
	DS1302_CLK=0;
	DS1302_RST=0;

}

void ds1302_write_reg(u8 addr,u8 dat)
{
	u8 i;
	DS1302_RST=0;
	sys_delay_about_us(DS1302_DELAY);
	DS1302_CLK=0;
	DS1302_RST=1;
	addr &= 0xFE;
	DS1302_DAT_OUT();
	sys_delay_about_us(DS1302_DELAY);
	for(i=0;i<8;i++)
	{
		DS1302_DAT=addr&0x01;
		DS1302_CLK=1;
		sys_delay_about_us(DS1302_DELAY);
		DS1302_CLK=0;
		sys_delay_about_us(DS1302_DELAY);
		addr >>= 1;
	}
	
	for(i=0;i<8;i++)
	{
		DS1302_DAT=dat&0x01;
		DS1302_CLK=1;
		sys_delay_about_us(DS1302_DELAY);
		DS1302_CLK=0;
		sys_delay_about_us(DS1302_DELAY);
		dat >>= 1;
	}
	
}

u8 ds1302_read_reg(u8 addr)
{
	u8 i;
	u8 temp;
	DS1302_RST=0;
	sys_delay_about_us(DS1302_DELAY);
	DS1302_CLK=0;
	DS1302_RST=1;
	addr |= 0x01;
	DS1302_DAT_OUT();
	sys_delay_about_us(DS1302_DELAY);
	for(i=0;i<8;i++)
	{
		DS1302_DAT=addr&0x01;
		DS1302_CLK=1;
		sys_delay_about_us(DS1302_DELAY);
		DS1302_CLK=0;
		sys_delay_about_us(DS1302_DELAY);
		addr >>= 1;
	}
	
	DS1302_DAT_IN();
	sys_delay_about_us(DS1302_DELAY);
	
	for(i=0;i<8;i++)
	{
		temp >>=1;
		if(DS1302_DAT)
			temp|=0x80;
		DS1302_CLK=1;
		sys_delay_about_us(DS1302_DELAY);
		DS1302_CLK=0;
		sys_delay_about_us(DS1302_DELAY);
	}
	DS1302_RST=0;
	return temp;
}

void ds1302_init_date()
{
	u8 i;
	ds1302_write_reg(DS1302_CTRL_ADDR,0x00);
	for(i=0;i<7;i++)
	{
		ds1302_write_reg(DS1302_SEC_ADDR+i*2,((u8*)&cur_date)[i]);
	}
	ds1302_write_reg(DS1302_CTRL_ADDR,0x80);

}


void ds1302_read_date()
{
	u8 i;
	for(i=0;i<7;i++)
	{
		((u8*)&cur_date)[i]=ds1302_read_reg(DS1302_SEC_ADDR+i*2);
	}

}
